package com.authine.cloudpivot.web.api.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.TaskReportFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.type.QueryDisplayType;
import com.authine.cloudpivot.web.Utils.ATSSignatureUtil;
import com.authine.cloudpivot.web.Utils.HttpClientUtils;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.service.AtsService;
import com.authine.cloudpivot.web.api.service.impl.RecruitmentServiceImpl;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api(value = "外企德科ATS对接接口", tags = "ats相关接口")
@RestController
@RequestMapping("/api/ats")
@Slf4j
public class AtsController extends BaseController {

    @Value("${ats.p_co_id}")
    private String p_co_id;
    @Value("${ats.url}")
    private String url;
    @Value("${ats.user_key}")
    private String user_key;
    @Value("${ats.secretKey}")
    private String secretKey;
    @Value("${ats.email}")
    private String email;
    @Value("${ats.url_append.create}")
    private String addUrl;
    @Value("${ats.createData.create}")
    private String createData;
    @Value("${ats.url_append.update}")
    private String updateUrl;
    @Value("${ats.createData.update}")
    private String updateData;
    @Value("${ats.url_append.weeklyReport}")
    private String weeklyReportUrl;
    @Value("${ats.createData.weeklyReport}")
    private String weeklyReportData;
    @Value("${ats.url_append.weeklyReportDetail}")
    private String weeklyReportDetailUrl;
    @Value("${ats.createData.weeklyReportDetail}")
    private String weeklyReportDetailData;

    @Autowired
    private AtsService atsService;

    @Reference(version = "1.00")
    private TaskReportFacade taskReportFacade;

    /**
     * ats同步数据，新增职位 招聘需求id
     * @param
     * @return
     */
    @ApiOperation(value = "ats同步数据，新增职位" )
    @GetMapping("/createPosition")
    @ResponseBody
    public ResponseResult<List<Map<String, Object>>> createPosition(String id){

        return getOkResponseResult(createAts(id),"success");
    }

    /**
     * ats同步数据，更改职位 招聘需求变更id
     * @param
     * @return
     */
    @ApiOperation(value = "ats同步数据，更改职位" )
    @GetMapping("/updatePosition")
    @ResponseBody
    public ResponseResult<List<Map<String, Object>>> updatePosition(String id){

        return getOkResponseResult(updateAts(id),"success");
    }

    /**
     * ats同步数据，关闭职位 招聘需求id
     * @param
     * @return
     */
    @ApiOperation(value = "ats同步数据，关闭职位" )
    @GetMapping("/closePosition")
    @ResponseBody
    public ResponseResult<List<Map<String, Object>>> closePosition(String id){

        return getOkResponseResult(closeAts(id),"success");
    }

    /**
     * ats周报接口
     * @param
     * @return:
     */
    @ApiOperation(value = "ats周报接口" )
    @GetMapping("/getAtsWeekData")
    @ResponseBody
    @Scheduled(cron = "0 58 23 ? * *")
    public ResponseResult<List<Map<String, Object>>> getAtsWeekData(){
        LocalDate today = LocalDate.now();
        LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
        boolean isLast = (Period.between(today, lastDayOfMonth).getDays()==0);
        //判断是否是周末
        DayOfWeek week = today.getDayOfWeek();
        List<Map<String, Object>> weeklyReport = getWeeklyReport(null);
        if(CollectionUtils.isEmpty(weeklyReport)){
            return getOkResponseResult(null,"不生成周报数据");
        }else{
            taskReportFacade.autoReviewReportMgrInfo();
            return getOkResponseResult(weeklyReport,"生成周报数据");
        }
    }

    @GetMapping("/getAtsWeekDataUse")
    @ResponseBody
    public ResponseResult<List<Map<String, Object>>> getAtsWeekDataUse(String time){
        List<Map<String, Object>> weeklyReport = getWeeklyReport(time);
        if(CollectionUtils.isEmpty(weeklyReport)){
            return getOkResponseResult(null,"不生成周报数据");
        }else{
            taskReportFacade.autoReviewReportMgrInfo();
            return getOkResponseResult(weeklyReport,"生成周报数据");
        }
    }

    /**
     * ats日报接口
     * @param
     * @return:
     */
    @ApiOperation(value = "ats日报接口" )
    @GetMapping("/getAtsDayData")
    @ResponseBody
    @Scheduled(cron = "0 58 23 ? * *")
    public ResponseResult<List<Map<String, Object>>> getAtsDayData(){
        //标签和标签时间
        LocalDateTime now = LocalDateTime.now();

        String signature = ATSSignatureUtil.getATSSignature(now,user_key,secretKey,weeklyReportDetailData);
        String call_time = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(now);
        //data数据
        Map<String, Object> data = new HashMap<>();
        data.put("queue", "");
        data.put("method", "weekly_report_detail");
        data.put("service", "position");
        //总数据
        Map<String, Object> map = new HashMap<>();
        map.put("call_time",call_time);
        map.put("signature",signature);
        map.put("userKey",user_key);
        map.put("data",data);
        //params数据
        Map<String, Object> params = new HashMap<>();
        params.put("pCoId", p_co_id);
        //查询时间段
        LocalDateTime minDay = now.minus(1, ChronoUnit.DAYS);
        params.put("startTime", minDay.toInstant(ZoneOffset.of("+8")).getEpochSecond());
        params.put("endTime", now.toInstant(ZoneOffset.of("+8")).getEpochSecond());
        map.put("params",params);
        String s = JSON.toJSONString(map);
        log.info("参数==" + s);
        String post = HttpClientUtils.jsonPost(url+weeklyReportDetailUrl, JSONObject.parseObject(s));
        log.info(post);
        Map<String, Object> postMap = JSON.parseObject(post, Map.class);
        List<Map<String, Object>> list = (List<Map<String, Object>>) postMap.get("data");
        atsService.saveWeeklyReportDetail(list);
        return getOkResponseResult(list,"生成日报数据");
    }

    /**
     * ats日报接口
     * @param
     * @return:
     */
    @ApiOperation(value = "ats日报接口" )
    @GetMapping("/getAtsDayDataUse")
    @ResponseBody
    public ResponseResult<List<Map<String, Object>>> getAtsDayDataUse(String start,String end){
        //标签和标签时间
        LocalDateTime now = LocalDateTime.now();

        String signature = ATSSignatureUtil.getATSSignature(now,user_key,secretKey,weeklyReportDetailData);
        String call_time = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(now);
        //data数据
        Map<String, Object> data = new HashMap<>();
        data.put("queue", "");
        data.put("method", "weekly_report_detail");
        data.put("service", "position");
        //总数据
        Map<String, Object> map = new HashMap<>();
        map.put("call_time",call_time);
        map.put("signature",signature);
        map.put("userKey",user_key);
        map.put("data",data);
        //params数据
        Map<String, Object> params = new HashMap<>();
        params.put("pCoId", p_co_id);
        //查询时间段
        LocalDateTime minDay = LocalDateTime.parse(start);
        LocalDateTime endDay = LocalDateTime.parse(end);
        params.put("startTime", minDay.toInstant(ZoneOffset.of("+8")).getEpochSecond());
        params.put("endTime", endDay.toInstant(ZoneOffset.of("+8")).getEpochSecond());
        map.put("params",params);
        String s = JSON.toJSONString(map);
        log.info("参数==" + s);
        String post = HttpClientUtils.jsonPost(url+weeklyReportDetailUrl, JSONObject.parseObject(s));
        log.info(post);
        Map<String, Object> postMap = JSON.parseObject(post, Map.class);
        List<Map<String, Object>> list = (List<Map<String, Object>>) postMap.get("data");
        atsService.saveWeeklyReportDetail(list);
        return getOkResponseResult(list,"生成日报数据");
    }

    private List<Map<String, Object>> createAts(String id){
        List<Map<String, Object>> list = new ArrayList<>();
        BizObjectFacade facade = this.getDubboConfigService().getBizObjectFacade();
        BizObjectCreatedModel bizObjectr = facade.getBizObject("recruitmentDemand", id);
        Map<String, Object> recruitmentDemand = bizObjectr.getData();
        //获取ats账号
        String atsUsername = MapUtils.getString(recruitmentDemand, "atsUsername", email);
        //招聘需求数据
        List<Map<String,Object>> demandDetails = (List<Map<String, Object>>) recruitmentDemand.get("demandDetails");
        Map<String, Map<String, Object>> projectNameMap = (Map<String, Map<String, Object>>) recruitmentDemand.get("projectName");
        Date demandEndTime = (Date) recruitmentDemand.get("demandEndTime");
        Date demandCreatedTime = (Date) recruitmentDemand.get("demandCreatedTime");
        //岗位jd数据
        Map<String, Map<String, Object>> jdMap = (Map<String, Map<String, Object>>) recruitmentDemand.get("postJD");
        BizObjectCreatedModel bizObjectj = facade.getBizObject("PostJD", MapUtils.getString(jdMap,"id"));
        Map<String, Object> jdData = bizObjectj.getData();
        String jdName = MapUtils.getString(jdData,"jobName");
        String degree = MapUtils.getString(jdData,"degree");
        Integer degreeType = getDegreeType(degree);
        String workyear = MapUtils.getString(jdData,"workyear");
        String[] workyears;
        if(workyear==null||!workyear.contains("-")){
            workyears = new String[]{"0", "1"};
        }else{
            workyears = workyear.split("-");
        }
        String salaryCalculationType = MapUtils.getString(jdData,"salaryCalculationType");
        //判断线上线下
        String recruitWay = MapUtils.getString(recruitmentDemand, "recruitWay");
        if("线下".equals(recruitWay)){
            for (Map<String, Object> demandDetail : demandDetails) {
                String demandDetailId = MapUtils.getString(demandDetail, "id");
                String storeCode = MapUtils.getString(demandDetail,"storeCode");
                String idCode = storeCode.concat("_").concat(demandDetailId);
                atsService.updateDemandDetail(demandDetailId,idCode,"");
            }
            return list;
        }
        //同步ats
        for (Map<String, Object> demandDetail : demandDetails) {
            String demandDetailId = MapUtils.getString(demandDetail, "id");
            //标签和标签时间
            LocalDateTime now = LocalDateTime.now();
            String signature = ATSSignatureUtil.getATSSignature(now,user_key,secretKey,createData);
            String call_time = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(now);
            //data数据
            Map<String, Object> data = new HashMap<>();
            data.put("queue", "");
            data.put("method", "create");
            data.put("service", "position");
            //params数据
            Map<String, Object> params = new HashMap<>();
            params.put("p_co_id", p_co_id);
            params.put("email", atsUsername);
            //岗位jd和门店生成
            String storeCode = MapUtils.getString(demandDetail,"storeCode");
            String idCode = storeCode.concat("_").concat(demandDetailId);
            params.put("third_party_jd_id",idCode);
            params.put("create_mode",12);
            //params--jd数据
            Map<String, Object> jd = new HashMap<>();
            String storeName = MapUtils.getString(demandDetail, "storeName");
            if(StringUtils.isNotBlank(storeName)){
                jd.put("name",storeName.concat("--").concat(jdName).concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
            }else{
                jd.put("name",jdName.concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
            }
            jd.put("client_name",MapUtils.getString(projectNameMap,"projectNames"));
            jd.put("order_demand_at",getTenTime(demandCreatedTime.getTime()));
            jd.put("order_start_at",getTenTime((new Date()).getTime()));
            jd.put("expect_completed_at",getTenTime(demandEndTime.getTime()));
            BigDecimal demandFor = (BigDecimal) demandDetail.get("demandFor");
            jd.put("number",demandFor.intValue());
            jd.put("salary_type",getSalaryCalculationType(salaryCalculationType));
            jd.put("degree_id",degreeType);
            jd.put("workyear_from",workyears[0]);
            jd.put("workyear_to",workyears[1]);
            jd.put("salary_begin",getCostByM(demandDetail.get("scale")));
            jd.put("salary_end",getCostByM(demandDetail.get("salaryCap")));
            jd.put("requirement",MapUtils.getString(jdData,"jobRequire"));
            jd.put("description",MapUtils.getString(jdData,"jobDuty"));
            jd.put("job_type",getJobType(MapUtils.getString(demandDetail,"jobNature")));
            Map<String, String> workplaces = new HashMap<>();
            Map<String, String> addressMap = new HashMap<>();
            addressMap.put("city",MapUtils.getString(demandDetail,"city"));
            addressMap.put("province",MapUtils.getString(demandDetail,"province"));
            Map<String, String> atsMap = atsService.getAtsMap(addressMap);
            String atsMapId = atsMap.get("id");
            String areas = MapUtils.getString(demandDetail,"areas");
            if(areas == null){
                areas = "";
            }
            workplaces.put("city_id",atsMapId);
            workplaces.put("address",areas.concat(MapUtils.getString(demandDetail,"address")));
            jd.put("workplaces",workplaces);
            List<String> advantages = new ArrayList<>();
            jd.put("advantages",advantages);
            jd.put("state",1);
            params.put("jd",jd);
            //总数据
            Map<String, Object> map = new HashMap<>();
            map.put("call_time",call_time);
            map.put("signature",signature);
            map.put("userKey",user_key);
            map.put("data",data);
            map.put("params",params);
            String s = JSON.toJSONString(map);
            log.info("参数==" + s);
            String post = HttpClientUtils.jsonPost(url+addUrl, JSONObject.parseObject(s));
            log.info(post);
            Map<String, Object> postMap = JSON.parseObject(post, Map.class);
            String atsId = (String) postMap.get("data");
            atsService.updateDemandDetail(demandDetailId,idCode,atsId);
            list.add(postMap);
        }
        return list;
    }

    private List<Map<String, Object>> updateAts(String id){
        List<Map<String, Object>> list = new ArrayList<>();
        BizObjectFacade facade = this.getDubboConfigService().getBizObjectFacade();
        BizObjectCreatedModel bizObjectr = facade.getBizObject("recruitmentDemandUpdate", id);
        Map<String, Object> recruitmentDemand = bizObjectr.getData();
        //招聘需求数据
        List<Map<String,Object>> demandDetails = (List<Map<String, Object>>) recruitmentDemand.get("demandDetailList");
        Map<String, Map<String, Object>> projectNameMap = (Map<String, Map<String, Object>>) recruitmentDemand.get("projectName");
        Date demandEndTime = (Date) recruitmentDemand.get("demandEndTime");
        Date demandCreatedTime = (Date) recruitmentDemand.get("demandCreatedTime");
        //岗位jd数据
        Map<String, Map<String, Object>> jdMap = (Map<String, Map<String, Object>>) recruitmentDemand.get("postJD");
        BizObjectCreatedModel bizObjectj = facade.getBizObject("PostJD", MapUtils.getString(jdMap,"id"));
        Map<String, Object> jdData = bizObjectj.getData();
        String jdName = MapUtils.getString(jdData,"jobName");
        String degree = MapUtils.getString(jdData,"degree");
        Integer degreeType = getDegreeType(degree);
        String workyear = MapUtils.getString(jdData,"workyear");
        String[] workyears;
        if(workyear==null||!workyear.contains("-")){
            workyears = new String[]{"0", "1"};
        }else{
            workyears = workyear.split("-");
        }
        String salaryCalculationType = MapUtils.getString(jdData,"salaryCalculationType");
        //判断线上线下
        String recruitWay = MapUtils.getString(recruitmentDemand, "recruitWay");
        if("线下".equals(recruitWay)){
            for (Map<String, Object> demandDetail : demandDetails) {
                String demandDetailId = MapUtils.getString(demandDetail, "id");
                String storeCode = MapUtils.getString(demandDetail,"storeCode");
                String idCode = storeCode.concat("_").concat(demandDetailId);
                atsService.updateDemandDetail(demandDetailId,idCode,"");
            }
            return list;
        }
        //同步ats
        for (Map<String, Object> demandDetail : demandDetails) {
            BigDecimal demandFor = (BigDecimal) demandDetail.get("newDemandFor");
            BigDecimal oldDemandFor = (BigDecimal) demandDetail.get("demandFor");
            BigDecimal hasHiredNum;
            if(demandDetail.get("hasHiredNum")==null){
                hasHiredNum = BigDecimal.ZERO;
            }else{
                hasHiredNum = (BigDecimal) demandDetail.get("hasHiredNum");
            }
            //if(MapUtils.getString(demandDetail,"state").equals("已取消")||MapUtils.getString(demandDetail,"state").equals("已完成")){
            //    continue;
            //}
            if((!(demandFor.compareTo(BigDecimal.ZERO) ==0)) && (!(demandFor.compareTo(hasHiredNum) ==0))){
                //标签和标签时间
                LocalDateTime now = LocalDateTime.now();
                String signature = ATSSignatureUtil.getATSSignature(now,user_key,secretKey,updateData);
                String call_time = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(now);
                //data数据
                Map<String, Object> data = new HashMap<>();
                data.put("queue", "");
                data.put("method", "update");
                data.put("service", "position");
                //params数据
                Map<String, Object> params = new HashMap<>();
                params.put("p_co_id", p_co_id);
                //params.put("email", email);
                //atsID
                params.put("jdId",MapUtils.getString(demandDetail,"atsId"));
                //岗位jd和门店生成
                String storeCode = MapUtils.getString(demandDetail,"storeCode");
                params.put("third_party_jd_id",MapUtils.getString(demandDetail,"idCode"));
                params.put("create_mode",12);
                //params--jd数据
                Map<String, Object> jd = new HashMap<>();
                jd.put("id",MapUtils.getString(demandDetail,"atsId"));
                String storeName = MapUtils.getString(demandDetail, "storeName");
                if(StringUtils.isNotBlank(storeName)){
                    jd.put("name",storeName.concat("--").concat(jdName).concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
                }else{
                    jd.put("name",jdName.concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
                }
                jd.put("client_name",MapUtils.getString(projectNameMap,"projectNames"));
                jd.put("order_demand_at",getTenTime(demandCreatedTime.getTime()));
                jd.put("order_start_at",getTenTime((new Date()).getTime()));
                jd.put("expect_completed_at",getTenTime(demandEndTime.getTime()));
                jd.put("number",demandFor.intValue());
                jd.put("salary_type",getSalaryCalculationType(salaryCalculationType));
                jd.put("degree_id",degreeType);
                jd.put("workyear_from",workyears[0]);
                jd.put("workyear_to",workyears[1]);
                jd.put("salary_begin",getCostByM(demandDetail.get("scale")));
                jd.put("salary_end",getCostByM(demandDetail.get("salaryCap")));
                jd.put("requirement",MapUtils.getString(jdData,"jobRequire"));
                jd.put("description",MapUtils.getString(jdData,"jobDuty"));
                jd.put("job_type",getJobType(MapUtils.getString(demandDetail,"jobNature")));
                Map<String, String> workplaces = new HashMap<>();
                Map<String, String> addressMap = new HashMap<>();
                addressMap.put("city",MapUtils.getString(demandDetail,"city"));
                addressMap.put("province",MapUtils.getString(demandDetail,"province"));
                Map<String, String> atsMap = atsService.getAtsMap(addressMap);
                String atsMapId = atsMap.get("id");
                String areas = MapUtils.getString(demandDetail,"areas");
                if(areas == null){
                    areas = "";
                }
                workplaces.put("city_id",atsMapId);
                workplaces.put("address",areas.concat(MapUtils.getString(demandDetail,"address")));
                jd.put("workplaces",workplaces);
                List<String> advantages = new ArrayList<>();
                jd.put("advantages",advantages);
                jd.put("state",1);
                params.put("jd",jd);
                //总数据
                Map<String, Object> map = new HashMap<>();
                map.put("call_time",call_time);
                map.put("signature",signature);
                map.put("userKey",user_key);
                map.put("data",data);
                map.put("params",params);
                String s = JSON.toJSONString(map);
                log.info("参数==" + s);
                String post = HttpClientUtils.jsonPost(url+updateUrl, JSONObject.parseObject(s));
                log.info(post);
                Map<String, Object> postMap = JSON.parseObject(post, Map.class);
                list.add(postMap);
            }else{
                //标签和标签时间
                LocalDateTime now = LocalDateTime.now();
                String signature = ATSSignatureUtil.getATSSignature(now,user_key,secretKey,updateData);
                String call_time = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(now);
                //data数据
                Map<String, Object> data = new HashMap<>();
                data.put("queue", "");
                data.put("method", "update");
                data.put("service", "position");
                //params数据
                Map<String, Object> params = new HashMap<>();
                params.put("p_co_id", p_co_id);
                //params.put("email", email);
                //atsID
                params.put("jdId",MapUtils.getString(demandDetail,"atsId"));
                //岗位jd和门店生成
                params.put("third_party_jd_id",MapUtils.getString(demandDetail,"idCode"));
                params.put("create_mode",12);
                //params--jd数据
                Map<String, Object> jd = new HashMap<>();
                String storeName = MapUtils.getString(demandDetail, "storeName");
                if(StringUtils.isNotBlank(storeName)){
                    jd.put("name",storeName.concat("--").concat(jdName).concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
                }else{
                    jd.put("name",jdName.concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
                }
                jd.put("client_name",MapUtils.getString(projectNameMap,"projectNames"));
                jd.put("order_demand_at",getTenTime(demandCreatedTime.getTime()));
                jd.put("order_start_at",getTenTime((new Date()).getTime()));
                jd.put("expect_completed_at",getTenTime(demandEndTime.getTime()));
                jd.put("salary_type",getSalaryCalculationType(salaryCalculationType));
                jd.put("degree_id",degreeType);
                jd.put("workyear_from",workyears[0]);
                jd.put("workyear_to",workyears[1]);
                jd.put("salary_begin",getCostByM(demandDetail.get("scale")));
                jd.put("salary_end",getCostByM(demandDetail.get("salaryCap")));
                jd.put("requirement",MapUtils.getString(jdData,"jobRequire"));
                jd.put("description",MapUtils.getString(jdData,"jobDuty"));
                jd.put("job_type",getJobType(MapUtils.getString(demandDetail,"jobNature")));
                Map<String, String> workplaces = new HashMap<>();
                Map<String, String> addressMap = new HashMap<>();
                addressMap.put("city",MapUtils.getString(demandDetail,"city"));
                addressMap.put("province",MapUtils.getString(demandDetail,"province"));
                Map<String, String> atsMap = atsService.getAtsMap(addressMap);
                String atsMapId = atsMap.get("id");
                String areas = MapUtils.getString(demandDetail,"areas");
                if(areas == null){
                    areas = "";
                }
                workplaces.put("city_id",atsMapId);
                workplaces.put("address",areas.concat(MapUtils.getString(demandDetail,"address")));
                jd.put("workplaces",workplaces);
                List<String> advantages = new ArrayList<>();
                jd.put("advantages",advantages);

                if(demandFor.compareTo(BigDecimal.ZERO) == 0){
                    jd.put("state",3);
                    jd.put("number",oldDemandFor.intValue());
                    jd.put("actual_canceled_at",getTenTime((new Date()).getTime()));
                }else if(demandFor.compareTo(hasHiredNum) == 0){
                    jd.put("state",2);
                    jd.put("number",demandFor.intValue());
                    jd.put("actual_completed_at",getTenTime((new Date()).getTime()));
                }
                params.put("jd",jd);
                //总数据
                Map<String, Object> map = new HashMap<>();
                map.put("call_time",call_time);
                map.put("signature",signature);
                map.put("userKey",user_key);
                map.put("data",data);
                map.put("params",params);
                String s = JSON.toJSONString(map);
                log.info("参数==" + s);
                String post = HttpClientUtils.jsonPost(url+updateUrl, JSONObject.parseObject(s));
                log.info(post);
                Map<String, Object> postMap = JSON.parseObject(post, Map.class);
                list.add(postMap);
            }

        }
        return list;
    }

    private List<Map<String, Object>> closeAts(String id){
        List<Map<String, Object>> list = new ArrayList<>();
        BizObjectFacade facade = this.getDubboConfigService().getBizObjectFacade();
        BizObjectCreatedModel bizObjectr = facade.getBizObject("recruitmentDemand", id);
        Map<String, Object> recruitmentDemand = bizObjectr.getData();
        //招聘需求数据
        List<Map<String,Object>> demandDetails = (List<Map<String, Object>>) recruitmentDemand.get("demandDetails");
        Map<String, Map<String, Object>> projectNameMap = (Map<String, Map<String, Object>>) recruitmentDemand.get("projectName");
        Date demandEndTime = (Date) recruitmentDemand.get("demandEndTime");
        Date demandCreatedTime = (Date) recruitmentDemand.get("demandCreatedTime");
        //岗位jd数据
        Map<String, Map<String, Object>> jdMap = (Map<String, Map<String, Object>>) recruitmentDemand.get("postJD");
        BizObjectCreatedModel bizObjectj = facade.getBizObject("PostJD", MapUtils.getString(jdMap,"id"));
        Map<String, Object> jdData = bizObjectj.getData();
        String jdName = MapUtils.getString(jdData,"jobName");
        String degree = MapUtils.getString(jdData,"degree");
        Integer degreeType = getDegreeType(degree);
        String workyear = MapUtils.getString(jdData,"workyear");
        String[] workyears;
        if(workyear==null||!workyear.contains("-")){
            workyears = new String[]{"0", "1"};
        }else{
            workyears = workyear.split("-");
        }
        String salaryCalculationType = MapUtils.getString(jdData,"salaryCalculationType");
        //判断线上线下
        String recruitWay = MapUtils.getString(recruitmentDemand, "recruitWay");
        if("线下".equals(recruitWay)){
            for (Map<String, Object> demandDetail : demandDetails) {
                String demandDetailId = MapUtils.getString(demandDetail, "id");
                String storeCode = MapUtils.getString(demandDetail,"storeCode");
                String idCode = storeCode.concat("_").concat(demandDetailId);
                atsService.updateDemandDetail(demandDetailId,idCode,"");
            }
            return list;
        }
        //同步ats
        for (Map<String, Object> demandDetail : demandDetails) {
            if(MapUtils.getString(demandDetail,"state").equals("已完成")){
                continue;
            }
            //标签和标签时间
            LocalDateTime now = LocalDateTime.now();
            String signature = ATSSignatureUtil.getATSSignature(now,user_key,secretKey,updateData);
            String call_time = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(now);
            //data数据
            Map<String, Object> data = new HashMap<>();
            data.put("queue", "");
            data.put("method", "update");
            data.put("service", "position");
            //params数据
            Map<String, Object> params = new HashMap<>();
            params.put("p_co_id", p_co_id);
            //params.put("email", email);
            //atsID
            params.put("jdId",MapUtils.getString(demandDetail,"atsId"));
            //岗位jd和门店生成
            params.put("third_party_jd_id",MapUtils.getString(demandDetail,"idCode"));
            params.put("create_mode",12);
            //params--jd数据
            Map<String, Object> jd = new HashMap<>();
            String storeName = MapUtils.getString(demandDetail, "storeName");
            if(StringUtils.isNotBlank(storeName)){
                jd.put("name",storeName.concat("--").concat(jdName).concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
            }else{
                jd.put("name",jdName.concat("--").concat(DateTimeFormatter.ofPattern("yyyyMMdd").format(now)));
            }
            jd.put("client_name",MapUtils.getString(projectNameMap,"projectNames"));
            jd.put("order_demand_at",getTenTime(demandCreatedTime.getTime()));
            jd.put("order_start_at",getTenTime((new Date()).getTime()));
            jd.put("actual_canceled_at",getTenTime((new Date()).getTime()));
            jd.put("expect_completed_at",getTenTime(demandEndTime.getTime()));
            BigDecimal demandFor = (BigDecimal) demandDetail.get("demandFor");
            jd.put("number",demandFor.intValue());
            jd.put("salary_type",getSalaryCalculationType(salaryCalculationType));
            jd.put("degree_id",degreeType);
            jd.put("workyear_from",workyears[0]);
            jd.put("workyear_to",workyears[1]);
            jd.put("salary_begin",getCostByM(demandDetail.get("scale")));
            jd.put("salary_end",getCostByM(demandDetail.get("salaryCap")));
            jd.put("requirement",MapUtils.getString(jdData,"jobRequire"));
            jd.put("description",MapUtils.getString(jdData,"jobDuty"));
            jd.put("job_type",getJobType(MapUtils.getString(demandDetail,"jobNature")));
            Map<String, String> workplaces = new HashMap<>();
            Map<String, String> addressMap = new HashMap<>();
            addressMap.put("city",MapUtils.getString(demandDetail,"city"));
            addressMap.put("province",MapUtils.getString(demandDetail,"province"));
            Map<String, String> atsMap = atsService.getAtsMap(addressMap);
            String atsMapId = atsMap.get("id");
            String areas = MapUtils.getString(demandDetail,"areas");
            if(areas == null){
                areas = "";
            }
            workplaces.put("city_id",atsMapId);
            workplaces.put("address",areas.concat(MapUtils.getString(demandDetail,"address")));
            jd.put("workplaces",workplaces);
            List<String> advantages = new ArrayList<>();
            jd.put("advantages",advantages);
            jd.put("state",3);
            params.put("jd",jd);
            //总数据
            Map<String, Object> map = new HashMap<>();
            map.put("call_time",call_time);
            map.put("signature",signature);
            map.put("userKey",user_key);
            map.put("data",data);
            map.put("params",params);
            String s = JSON.toJSONString(map);
            log.info("参数==" + s);
            String post = HttpClientUtils.jsonPost(url+updateUrl, JSONObject.parseObject(s));
            log.info(post);
            Map<String, Object> postMap = JSON.parseObject(post, Map.class);
            list.add(postMap);
        }
        return list;
    }

    private List<Map<String, Object>> getWeeklyReport(String time){
        //标签和标签时间
        LocalDateTime now = LocalDateTime.now();

        //获取需要查询的周报atsid
        List<String> weeklyIds = new ArrayList<>();
        if(StringUtils.isNotBlank(time)){
            weeklyIds = atsService.getWeeklyReport(LocalDateTime.parse(time));
            atsService.updateAll(LocalDateTime.parse(time));
        }else{
            weeklyIds = atsService.getWeeklyReport(now);
            atsService.updateAll(now);
        }
        if(CollectionUtils.isEmpty(weeklyIds)){
            return null;
        }
        String signature = ATSSignatureUtil.getATSSignature(now,user_key,secretKey,weeklyReportData);
        String call_time = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(now);
        //data数据
        Map<String, Object> data = new HashMap<>();
        data.put("queue", "");
        data.put("method", "weekly_report");
        data.put("service", "position");
        //总数据
        Map<String, Object> map = new HashMap<>();
        map.put("call_time",call_time);
        map.put("signature",signature);
        map.put("userKey",user_key);
        map.put("data",data);
        //params数据
        Map<String, Object> params = new HashMap<>();
        params.put("p_co_id", p_co_id);
        params.put("email", email);
        //查询时间段
        int dayOfMonth = now.getDayOfMonth();
        LocalDateTime minDay;
        if(dayOfMonth>=7){
            minDay = now.minus(1, ChronoUnit.WEEKS);
        }else{
            minDay = now.minusDays(dayOfMonth);
        }
        params.put("startTime", minDay.toInstant(ZoneOffset.of("+8")).getEpochSecond());
        params.put("endTime", now.toInstant(ZoneOffset.of("+8")).getEpochSecond());
        params.put("jdIds",weeklyIds.toArray());
        map.put("params",params);
        String s = JSON.toJSONString(map);
        log.info("参数==" + s);
        String post = HttpClientUtils.jsonPost(url+weeklyReportUrl, JSONObject.parseObject(s));
        log.info(post);
        Map<String, Object> postMap = JSON.parseObject(post, Map.class);
        List<Map<String, Object>> datas = (List<Map<String, Object>>) postMap.get("data");

        List<Map<String, Object>> updateData = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(datas)){
            for (Map<String, Object> mapd : datas) {
                Map<String, Object> updateMap = new HashMap<>();
                String jdId = MapUtils.getString(mapd, "jdId");
                Integer userSelect = MapUtils.getInteger(mapd, "userSelect");
                Integer userInterview = MapUtils.getInteger(mapd, "userInterview");
                Integer userPush = MapUtils.getInteger(mapd, "userPush");
                Integer customerInterview = MapUtils.getInteger(mapd, "customerInterview");
                Integer acceptOffer = MapUtils.getInteger(mapd, "acceptOffer");
                Integer entry = MapUtils.getInteger(mapd, "entry");
                updateMap.put("atsId",jdId);
                updateMap.put("userSelect",getValue(userInterview));
                updateMap.put("userPush",getValue(userPush));
                updateMap.put("customerInterview",getValue(customerInterview));
                updateMap.put("acceptOffer",getValue(acceptOffer));
                updateMap.put("entry",getValue(entry));
                updateMap.put("chargeBy",MapUtils.getString(mapd,"chargeByName"));
                if(StringUtils.isNotBlank(time)){
                    updateMap.put("now",LocalDateTime.parse(time));
                }else{
                    updateMap.put("now",now);
                }
                updateData.add(updateMap);
            }
        }
        if(CollectionUtils.isNotEmpty(updateData)){
            atsService.updateWeeklyReport(updateData);
            atsService.updateWeeklySumReport(updateData);
        }
        return updateData;
    }

    private Integer getCostByM(Object costo){
        if(costo==null){
            return 0;
        }
        BigDecimal cost = (BigDecimal) costo;
        BigDecimal costM = cost.multiply(BigDecimal.valueOf(100)).setScale(0);
        return Integer.valueOf(costM.toString());
    }

    private Long getTenTime(long time){
        return time / 1000;
    }

    private Integer getSalaryCalculationType(String type){
        if(type==null){
            return 0;
        }
        switch (type){
            case "面议":
                return 0;
            case "年薪":
                return 1;
            case "月薪":
                return 2;
            case "日薪":
                return 3;
            case "时薪":
                return 4;
            case "周薪":
                return 5;
            case "双周薪":
                return 6;
            default:
                return 0;
        }
    }

    private Integer getJobType(String type){
        if(type==null){
            return 1;
        }
        switch (type){
            case "全职":
                return 1;
            case "兼职":
                return 2;
            case "实习生":
                return 3;
            default:
                return 1;
        }
    }

    private Integer getDegreeType(String type){
        if(type==null){
            return 1;
        }
        switch (type){
            case "本科":
                return 1;
            case "硕士":
                return 2;
            case "博士":
                return 3;
            case "专科":
                return 4;
            case "博士后":
                return 10;
            case "初中":
                return 86;
            case "职高":
                return 87;
            case "高中":
                return 89;
            case "中专":
                return 90;
            case "中技":
                return 91;
            case "专升本":
                return 92;
            default:
                return 1;
        }
    }

    private Integer getValue(Integer value){
        return value == null ? 0 : value;
    }
}
